<?php
namespace app\system;
defined('IN_SYSTEM') or die('Access Denied');
class upgrade
{
    public function __construct()
    {
        $this->db_pre = config('database.connections.mysql.prefix');
        $this->Db = new \think\facade\Db();
    }

    public function run($table_pre){
        $this->table_pre = $table_pre;
        try{
            $info = include_once(root_path() . 'version.php');
            $sql = $this->sql();
            if($info['hiphp']['version'] == '1.3.5'){
                $res = $this->v135();
            }
            return true;
        }catch (\Exception $e){
            \think\facade\Log::write($e->getMessage().$e->getFile().$e->getLine(), 'error');
            return $e->getMessage();
        }
    }

    public function field_exist($field, $table){
        $fields = getDbFields($table);
        if(in_array($field, $fields)){
            return false;
        }
        return true;
    }

    protected function field_add($fields, $table){
        if(!empty($fields)){
            foreach ($fields as $v){
                if(true === $this->field_exist($v['name'], $table)){
                    $other = '';
                    if(!empty($v['default'])){
                        $other .= " default `".$v['default']."`";
                    }
                    if(!empty($v['comment'])){
                        $other .= " comment '".$v['comment']."'";
                    }
                    if(!empty($other)){
                        $other = rtrim($other);
                    }
                    $this->Db::query("ALTER TABLE `" . $this->db_pre . $table . "` ADD `".$v['name']."` ".$v['type'] . $other . " AFTER `".$v['after']."`");
                }
            }
            return true;
        }
        return false;
    }

    protected function sql(){
        $sqlFile = dirname(__FILE__).'/../sql/upgrade.sql';
        if (file_exists($sqlFile)) {
            $sql = file_get_contents($sqlFile);
            $sqlList = parseSql($sql, 0, ['pre_' => $this->table_pre]);
            if ($sqlList) {
                $sqlList = array_filter($sqlList);
                foreach ($sqlList as $v) {
                    try {
                        $this->Db::execute($v);
                    } catch (\Exception $e) {
                        return $e->getMessage();
                    }
                }
            }
        }
    }

    protected function v135(){
        $this->Db::query("ALTER TABLE `" . $this->db_pre . "system_menu` ADD UNIQUE KEY `module_title_url` (`module`,`title`,`url`)");
        return true;
    }
}